package com.sqoq.downloader3.retrofit;

import com.sqoq.downloader3.BuildConfig;
import com.sqoq.downloader3.retrofit.MHttpLoggingInterceptor;
import com.orhanobut.logger.AndroidLogAdapter;
import com.orhanobut.logger.FormatStrategy;
import com.orhanobut.logger.Logger;
import com.orhanobut.logger.PrettyFormatStrategy;

import org.json.JSONArray;
import org.json.JSONObject;

public class HttpLogger implements MHttpLoggingInterceptor.Logger {
    public HttpLogger() {
        FormatStrategy formatStrategy = PrettyFormatStrategy.newBuilder()
                .showThreadInfo(false)  // (Optional) Whether to show thread info or not. Default true
                .methodCount(0)         // (Optional) How many method line to show. Default 2
                .methodOffset(7)        // (Optional) Hides internal method calls up to offset. Default 5
//                .logStrategy(customLog) // (Optional) Changes the log strategy to print out. Default LogCat
                .tag("HTTPLOG")   // (Optional) Global tag for every log. Default PRETTY_LOGGER
                .build();

        Logger.addLogAdapter(new AndroidLogAdapter(formatStrategy) {
            @Override
            public boolean isLoggable(int priority, String tag) {
                return BuildConfig.DEBUG;
            }
        });
    }

    @Override
    public void log(String message) {
        if (isJson(message)) {
            Logger.json(message);
        } else if (message.startsWith("<!DOCTYPE")) {
            Logger.xml(message);
        } else {
            Logger.d(message);
        }
    }

    public static boolean isJson(String content) {
        if (content == null) {
            return false;
        }
        boolean isJsonObject = true;
        boolean isJsonArray = true;
        try {

            new JSONObject(content);
        } catch (Exception e) {
            isJsonObject = false;
        }
        try {
            new JSONArray(content);
        } catch (Exception e) {
            isJsonArray = false;
        }
        if (!isJsonObject && !isJsonArray) {
            return false;
        }
        return true;
    }
}
